package com.it.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.it.reggie.commen.R;
import com.it.reggie.entity.Category;
import com.it.reggie.entity.Dish;
import com.it.reggie.entity.DishDto;
import com.it.reggie.entity.Setmeal;
import com.it.reggie.service.CategoryService;
import com.it.reggie.service.DishService;
import com.it.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
@SuppressWarnings(value = "all")
public class CategoryController {


    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    //添加菜品分类
    @PostMapping
    public R add(@RequestBody Category category, HttpServletRequest request) {

        categoryService.save(category);

        return R.success("添加成功");

    }

    //分页查询
    @GetMapping("/page")
    public R selectByPage(Integer page, Integer pageSize) {

        IPage<Category> iPage = new Page<>(page, pageSize);

        categoryService.page(iPage, null);

        return R.success(iPage);

    }


    //根据ID删除
    @DeleteMapping
    public R delete(Long id) {

        Dish dish = new Dish();

        dish.setCategoryId(id);

        LambdaQueryWrapper<Dish> qwDish = new LambdaQueryWrapper<>();

        qwDish.eq(Dish::getCategoryId, id);

        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Setmeal::getCategoryId, id );
        List<Setmeal> list1 = setmealService.list(queryWrapper);


        List<Dish> list = dishService.list(qwDish);

        if (list.size()==0 && list1.size()==0) {

            LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();

            qw.eq(id != null, Category::getId, id);

            categoryService.remove(qw);

            return R.success("删除成功");
        }else {

            return R.error("删除失败");

        }

    }

    //根据ID修改
    @PutMapping
    public R upDateById(@RequestBody Category category, HttpServletRequest request) {

        Long id1 = category.getId();

        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();

        qw.eq(id1 != null, Category::getId, id1);


        categoryService.update(category, qw);

        return R.success("修改成功");

    }

    @GetMapping("/list")
    public R list(Integer type) {

        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        qw.eq(type != null, Category::getType, type);
        List<Category> list = categoryService.list(qw);

        return R.success(list);

    }

}
